package com.boco.blch.runner.result.handler;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.boco.blch.runner.result.Result;

public class TrimResult implements ResultHandler {
	public static final String LINE_SEPARATOR = System.getProperty("line.separator");
	/*匹配命令行提示的正则*/
	private static final String PROMPT_REGEX = "\\[.+?@.+?\\][#$]\\s*";
	private static Pattern prompt = Pattern.compile(PROMPT_REGEX);
	/*匹配上次登录信息正则*/
	private static final String LOGIN_REGEX = "Last login:.+from.+";
	private static Pattern login = Pattern.compile(LOGIN_REGEX);
	/*匹配chmod指令正则*/
	private static final String CHMOD_REGEX = "chmod\\s+?\\+x\\s[0-9a-zA-Z]{32}\\.sh";
	private static Pattern chmod = Pattern.compile(CHMOD_REGEX);
	/*匹配执行指令正则*/
	protected static final String EXESHELL_REGEX = "\\./[0-9a-zA-Z]{32}\\.sh";
	private static Pattern exeshell = Pattern.compile(EXESHELL_REGEX);
	@Override
	public Result handler(Result r) {
		String[] lines = r.getMessage().split("\n");
		StringBuilder message = new StringBuilder();
		for(String line : lines){
			if(!isPromt(line) && !isLoginInfo(line) && !line.equals(""))
				message.append(line).append("\n");
		}
		/*第一次过滤后，如果生成的结果前两行为
		     第一排：chmod +x [0-9a-zA-Z]{32}.sh 
		     第二排：./[0-9a-zA-Z]{32}.sh 
		     就删除*/
		message = checkFirst2Rows(message);
		
		r.setMessage(message.toString().trim());
		return r;
	}
	
	private StringBuilder checkFirst2Rows(StringBuilder message) {
		String[] lines = message.toString().split("\n");
		StringBuilder ret = message;
		int length = lines.length;
		if(lines != null && length >= 2){
			if(isChmod(lines[0]) && isExec(lines[1])){
				ret = new StringBuilder();
				for(int i = 2; i < length; i++){
					ret.append(lines[i]).append("\n");
				}
			}
			
		}
		return ret;
	}

	private static boolean isPromt(String message){
		 Matcher m = prompt.matcher(message);
		 return m.find();
	}
	
	private static boolean isLoginInfo(String message){
		 Matcher m = login.matcher(message);
		 return m.find();
	}
	
	private static boolean isChmod(String message){
		 Matcher m = chmod.matcher(message);
		 return m.find();
	}
	
	private static boolean isExec(String message){
		 Matcher m = exeshell.matcher(message);
		 return m.find();
	}
	
	


}
